<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="900"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    @close="closeDialog(false)"
  >
    <el-form ref="addOrEditFormRef" v-loading="loading" :model="formData" :rules="rules" label-width="170" size="">
      <el-row justify="start" class="d_left">
        <el-col :span="12" class="">
          <el-form-item label="账户编号" prop="code">
            <el-input v-model="formData.code" disabled placeholder="自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="担保银行账户名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入担保银行账户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="担保银行统一信用代码" prop="socialcreditcode">
            <el-input v-model="formData.socialcreditcode" placeholder="请输入担保银行信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="开户银行" prop="bankName">
            <!-- <el-input v-model="formData.bankName" placeholder="请输入开户银行名称" /> -->
            <el-select v-model="formData.bankName" placeholder="请选择">
              <el-option v-for="item in bankTypeTypes" :key="item.label" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="开户银行账号" prop="bankNo">
            <el-input v-model="formData.bankNo" placeholder="请输入开户银行账号" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传银行保函附件信息" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ProjectGuaranteeAccountEditForm } from "@/api/guarantee/types";
import { Except, Ride } from "@/utils/decimal";
import { getDicts } from "@/store/modules/dict";
import { CheckSocialCreditCode } from "@/utils/verify";

import MoneyInput from "@/components/MoneyInput/index.vue";
import {
  CreateProjectGuaranteeAccount,
  UpdateProjectGuaranteeAccount,
  GetProjectGuaranteeAccount,
} from "@/api/guarantee/index";
import { FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";
//上传地址
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);

const bankTypeTypes = getDicts("bankTypeTypes");

const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "创建银行保函账户",
      footBtn: "核实账户信息",
      id: 0,
    }),
  },
});

//上传文件列表
const fileList = ref<UploadUserFile[]>([]);

const { dialogAddOrEdit } = toRefs(props);

const emit = defineEmits(["sendClose"]);

const loading = ref(false);
const formData = reactive<ProjectGuaranteeAccountEditForm>({});
const addOrEditFormRef = ref(ElForm);

//表单验证
const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传附件!"));
    return;
  } else {
    callback();
  }
};

/* 统一社会信用代码检查 */
const SocialCreditCodeBlur = (rule: any, value: any, callback: any) => {
  if (!value || value === undefined || value === "") {
    callback("请输入正确的统一社会信用代码");
    return;
  }
  if (value.length < 18) {
    callback("请输入正确的统一社会信用代码");
    return;
  }
  let check = CheckSocialCreditCode(value);
  if (check) {
    callback();
  } else {
    callback("请输入正确的统一社会信用代码");
  }
};
const rules = reactive<FormRules<ProjectGuaranteeAccountEditForm>>({
  name: [{ required: true, message: "请输入担保银行账户名称", trigger: "blur" }],
  socialcreditcode: [{ required: true, trigger: "blur", validator: SocialCreditCodeBlur }],
  bankName: [{ required: true, message: "请选择开户银行", trigger: "blur" }],
  bankNo: [{ required: true, message: "请输入开户银行账号", trigger: "blur" }],
  attachments: [
    {
      required: true,
      message: "请上传银行保函附件信息",
      trigger: "blur",
      validator: validatorAttachment,
    },
  ],
});

onMounted(() => {
  loading.value = true;
  let id = 0;
  if (dialogAddOrEdit.value.id) {
    id = dialogAddOrEdit.value.id;
  }
  GetProjectGuaranteeAccount(id)
    .then((res) => {
      Object.assign(formData, res.data);
      if (res.data.attachmentFiles) {
        let list = Array<any>();
        res.data.attachmentFiles.forEach((item: any) => {
          list.push({
            name: item.friendlyName,
            url: item.objectFilePath,
            status: "success",
            uid: item.id,
          });
        });
        fileList.value = list;
      }
    })
    .finally(() => {
      loading.value = false;
    });
});

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

/**
 * 关闭弹窗
 */
function closeDialog(query: boolean, data?: any) {
  emit("sendClose", query, data);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.id = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      formData.type = 4; //创建银行保函
      if (fileList.value.length > 0) {
        let uplist = new Array<any>();
        fileList.value.forEach((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              uplist.push({ attachmentId: item.response.data });
            } else {
              uplist.push({ attachmentId: item.uid });
            }
          }
        });
        formData.attachments = uplist;
      }
      let submitForm = Object.assign({}, formData);
      if (dialogAddOrEdit.value.id) {
        UpdateProjectGuaranteeAccount(submitForm)
          .then((res) => {
            if (res.success) {
              closeDialog(true);
            }
          })
          .finally(() => (loading.value = false));
        return;
      }
      CreateProjectGuaranteeAccount(submitForm)
        .then((res) => {
          if (res.success) {
            closeDialog(true);
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}
</script>

<style lang="scss" scoped>
.d_left {
  margin-left: 10px;
}
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 80%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
